package com.runfast.waimai.web.controller.goods;


import com.google.common.base.Joiner;
import com.runfast.common.utils.SessionContext;
import com.runfast.common.web.entity.Result;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * ${DESCRIPTION}外卖商品管理
 *
 * @author chenzheng
 * @create 2018-05-08 20:06
 **/
@RestController("goodsSellController")
@RequestMapping("/server/goodsSell")
public class GoodsSellController {
    @Autowired
    private RunfastBusinessService runfastBusinessService;
    @Autowired
    private RunfastGoodsSellService runfastGoodsSellService;
    @Autowired
    private RunfastGoodsSellStandardService runfastGoodsSellStandardService;
    @Autowired
    private RunfastGoodsSellOptionService runfastGoodsSellOptionService;
    @Autowired
    private RunfastGoodsSellSubOptionService runfastGoodsSellSubOptionService;
    @Autowired
    private WaiMaiRunfastAgentbusinessService waiMaiRunfastAgentbusinessService;
    /**
     * 商品列表带分页的
     */
    @GetMapping("/list")
    public Result list(@PageableDefault Pageable pageable, RunfastGoodsSell goodsSell){
        Map<Object,Object> map1=new HashMap<Object, Object>();
        if(goodsSell!=null){
            if(StringUtils.isNotBlank(goodsSell.getName())){
                map1.put("name",goodsSell.getName());
            }
            if(goodsSell.getStatus()!=null){
                map1.put("status",goodsSell.getStatus());
            }
            if(StringUtils.isNotBlank(goodsSell.getBusinessname())){
                map1.put("businessname",goodsSell.getBusinessname());
            }
            /**代理商多选*/
            if(StringUtils.isNotBlank(goodsSell.getAgentIds())){
               map1.put("agentIds",goodsSell.getAgentIds());
            }
            if(goodsSell.getMainClassId()!=null){
                map1.put("mainClassId",goodsSell.getMainClassId());
            }
        }
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        RunfastBusinessAccounts accounts = SessionContext.getRunfastBusinessAccounts();
        Map<Object,Object> map=new HashMap<Object, Object>();

        if(admin!=null && admin.getType()==3  && accounts!=null){
            //商家帐号登录----只能看自己商家的
        }else if(admin!=null && admin.getType()==2 && agentAccounts!=null){
            //代理商
            if(StringUtils.isEmpty(goodsSell.getAgentIds())){
                map1.put("agentIds",agentAccounts.getAgentid());
            }
        }else if(admin !=null  &&   admin.getType()==1){
            //后台管理员---查看全部的
            if(admin.getAgents().size()>0){
                if(StringUtils.isEmpty(goodsSell.getAgentIds())){
                    map1.put("agentIds", Joiner.on(",").join(admin.getAgents()) );
                }
            }
        }
        map1.put("pageable",pageable);
        List<RunfastGoodsSell> list=runfastGoodsSellService.selectByExampleAndBusinessWithPageable(map1);
        if(list.size()>0){
             list=runfastGoodsSellService.setStandardListAndOptionList(list);
             for(RunfastGoodsSell goodsSell1:list){
                 if(goodsSell1.getAgentid()!=null){
                     WaiMaiRunfastAgentbusiness  agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(goodsSell1.getAgentid());
                     if(agentbusiness!=null){
                         goodsSell1.setAgentname(agentbusiness.getName());
                     }
                 }
             }
        }
        Integer total=runfastGoodsSellService.countByExampleAndBusiness(map1);
        map.put("list",list);
        map.put("total",total);
        return Result.ok(null,map);
    }

    /**
     * 商品列表
     */
   /* @GetMapping("/select")
    @RequiresPermissions("server:goodsSell:select")
    public Result select(){
        List<RunfastGoodsSell> list = runfastGoodsSellService.selectByExample(null);
        return Result.ok(null,list);
    }*/


    /**
     * 商品信息
     */
    @GetMapping("/info")
    public Result info(Integer id){
        if(id==null){return Result.fail(null,"商品id不能为空！");}
        RunfastGoodsSell goodsSell=runfastGoodsSellService.selectByPrimaryKey(id);
        if(goodsSell!=null){
            Map<Object,Object> map =runfastGoodsSellService.selectBygoodsId(goodsSell);
            goodsSell.setStandardList((List<RunfastGoodsSellStandard>)map.get("standards"));
            goodsSell.setOptionList((List<RunfastGoodsSellOption>)map.get("optionList"));
        }else{return Result.fail(null,"对应的商品不存在！");}
        return Result.ok(null,goodsSell);
    }


    /**
     * 保存商品
     */
    @PostMapping("/save")
    public Result save(@Validated({RunfastGoodsSell.GroupA.class}) @RequestBody RunfastGoodsSell goodsSell , BindingResult result){
        if(result.hasErrors()){
            return Result.fail(null,result.getFieldError().getDefaultMessage());
        }else{
            if(!(goodsSell.getStandardList().size()>0)){
                return Result.fail(null,"至少有一个规格");
            }
            if(goodsSell.getBusinessid()==null){return Result.fail(null,"商品必须有所属的商家！");}
            if(goodsSell.getBusinessid()!=null ){
                RunfastBusiness b = runfastBusinessService.selectByPrimaryKey(goodsSell.getBusinessid());
                if(b==null){return Result.fail(null,"没找到对应的商家！");}
                if(b!=null){
                    goodsSell.setBusinessid(b.getId());
                    goodsSell.setBusinessname(b.getName());
                    goodsSell.setAgentid(b.getAgentid());
                    goodsSell.setAgentname(b.getAgentname());

                    RunfastGoodsSellExample example=new RunfastGoodsSellExample();
                    example.createCriteria().andAgentidEqualTo(b.getAgentid()).andBusinessidEqualTo(b.getId()).andDeletedNotEqualTo(1).andSelltypeidEqualTo(goodsSell.getSelltypeid());
                    Integer total=runfastGoodsSellService.countByExample(example);
                    if(total==0){
                        goodsSell.setSort(0);
                    }else{
                        goodsSell.setSort(total);
                    }
                }
            }
            if(goodsSell.getMinNum()==null){
                goodsSell.setMinNum(1);
            }
            if(goodsSell.getStatus()==null){goodsSell.setStatus(0);}
            goodsSell.setCreatetime(new Date());
            goodsSell.setDeleted(0);
            if(goodsSell.getRequired()==null){
                goodsSell.setRequired(false);
            }
            runfastGoodsSellService.insertSelective(goodsSell);
            for(RunfastGoodsSellStandard standard:goodsSell.getStandardList()){
                standard.setBusinessid(goodsSell.getBusinessid());
                standard.setGoodssellid(goodsSell.getId());
                standard.setBusinessname(goodsSell.getBusinessname());
                if(standard.getFullNum()==null){
                    standard.setFullNum(false);
                }
                if(standard.getDeleted()==null){
                    standard.setDeleted(false);
                }
                runfastGoodsSellStandardService.insertSelective(standard);
            }
            runfastGoodsSellService.updateNum(goodsSell);
            if(goodsSell.getOptionList().size()>0){
                runfastGoodsSellOptionService.saveOPtionsAndSubOptions(goodsSell);
            }
        }
        return Result.ok(null);
    }

    /**
     * 修改商品
     */
    @PostMapping("/update")
    public Result update(@Validated({RunfastGoodsSell.GroupB.class}) @RequestBody RunfastGoodsSell goodsSell , BindingResult result){
        if(result.hasErrors()){
            return Result.fail(null,result.getFieldError().getDefaultMessage());
        }else{
            if(!(goodsSell.getStandardList().size()>0)){
                return Result.fail(null,"至少有一个规格");
            }
            BaseUser admin = SessionContext.getAdmin();
            WaiMaiRunfastAgentaccounts accounts= SessionContext.getCurrentRunfastAgentaccounts();
            RunfastBusinessAccounts businessAccounts = SessionContext.getRunfastBusinessAccounts();
            if(goodsSell.getBusinessid()!=null ){
                RunfastBusiness b = runfastBusinessService.selectByPrimaryKey(goodsSell.getBusinessid());
                if(b==null){return Result.fail(null,"对应的商家不存在！");}
                RunfastGoodsSell old = runfastGoodsSellService.selectByPrimaryKey(goodsSell.getId());
                if(old!=null){
                    if(admin!=null && admin.getType()==2 && accounts!=null && !accounts.getAgentid().equals(old.getAgentid())){
                        return Result.fail(null,"只能修改自己名下商家的商品！");
                    }
                    if(admin!=null && admin.getType()==3 && businessAccounts!=null && !businessAccounts.getBusinessid().equals(old.getBusinessid())){
                        return Result.fail(null,"只能修改自己名下商家的商品！");
                    }
                }
            }
            if(goodsSell.getId()==null){return Result.fail(null,"商品的主键不能为空！");}
            runfastGoodsSellService.update(goodsSell);
            runfastGoodsSellService.updateNum(goodsSell);
        }
        return Result.ok(null);
    }

    /**
     * 删除商品----单个或者批量
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody RunfastGoodsSell sell){
        if(sell!=null && sell.getIds().size()>0){
            for(Integer id:sell.getIds()){
                RunfastGoodsSell   goodsSell=runfastGoodsSellService.selectByPrimaryKey(id);
                if(goodsSell!=null){
                    goodsSell.setDeleted(1);
                    runfastGoodsSellService.updateByPrimaryKeySelective(goodsSell);
                    //删除规格
                    RunfastGoodsSellStandardExample example=new RunfastGoodsSellStandardExample();
                    example.createCriteria().andBusinessidEqualTo(goodsSell.getBusinessid()).andGoodssellidEqualTo(goodsSell.getId()).andDeletedNotEqualTo(true);
                    List<RunfastGoodsSellStandard> list=runfastGoodsSellStandardService.selectByExample(example);
                    if(list.size()>0){
                        for(RunfastGoodsSellStandard sellStandard:list){
                            sellStandard.setDeleted(true);
                            runfastGoodsSellStandardService.updateByPrimaryKeySelective(sellStandard);
                        }
                    }
                    //删除属性
                    RunfastGoodsSellOptionExample optionExample=new RunfastGoodsSellOptionExample();
                    optionExample.createCriteria().andGoodssellidEqualTo(goodsSell.getId()).andBusinessidEqualTo(goodsSell.getBusinessid()).andDeletedNotEqualTo(true);
                    List<RunfastGoodsSellOption> optionList=runfastGoodsSellOptionService.selectByExample(optionExample);
                    if(optionList.size()>0){
                        for(RunfastGoodsSellOption option:optionList){
                            option.setDeleted(true);
                            runfastGoodsSellOptionService.updateByPrimaryKeySelective(option);
                            RunfastGoodsSellSubOptionExample example1=new RunfastGoodsSellSubOptionExample();
                            example1.createCriteria().andOptionidEqualTo(option.getId()).andDelNotEqualTo(1).andBusinessidEqualTo(option.getBusinessid()).andGoodssellidEqualTo(option.getGoodssellid());
                            List<RunfastGoodsSellSubOption> sellSubOptionList=runfastGoodsSellSubOptionService.selectByExample(example1);
                            if(sellSubOptionList.size()>0){
                                for(RunfastGoodsSellSubOption subOption:sellSubOptionList){
                                    subOption.setDel(1);
                                    runfastGoodsSellSubOptionService.updateByPrimaryKeySelective(subOption);
                                }
                            }
                        }
                    }
                }else{return Result.fail(null,"此商品不存在！");}
            }
        }else{
            return Result.fail(null,"商品id不能为空");
        }
        return Result.ok(null);
    }

    /**上下架，单个及多个*/
    @PostMapping("/setStatus")
    public Result setStatus(@RequestBody RunfastGoodsSell sell){
        if(sell!=null && sell.getIds().size()>0 && sell.getStatus()!=null){
            //状态 0正常销售 1：暂停销售 2：商品下架

            for(Integer id:sell.getIds()){
                RunfastGoodsSell   goodsSell=runfastGoodsSellService.selectByPrimaryKey(id);
                if(goodsSell!=null){
                    goodsSell.setStatus(sell.getStatus());
                    runfastGoodsSellService.updateByPrimaryKeySelective(goodsSell);
                }
            }
        }
      return Result.ok(null);
    }


    /**
     * 每天零点把规格表中full_num=true的库存设置为num=10000
     * */
    public  void setNumFull(){
        RunfastGoodsSellStandardExample example=new RunfastGoodsSellStandardExample();
        example.createCriteria().andFullNumEqualTo(true);
        List<RunfastGoodsSellStandard> list=runfastGoodsSellStandardService.selectByExample(example);
        if(list.size()>0){
            for(RunfastGoodsSellStandard standard:list){
                standard.setNum(10000);
                standard.setFullNum(false);
                runfastGoodsSellStandardService.updateByPrimaryKeySelective(standard);
                RunfastGoodsSell goodsSell=new RunfastGoodsSell();
                goodsSell.setId(standard.getGoodssellid());
                goodsSell.setBusinessid(standard.getBusinessid());
                runfastGoodsSellService.updateNum(goodsSell);
            }
        }
    }

    /**批量处理:属性，规格,餐盒费，商品分类*/
    @PostMapping("/batchOperating")
    public Result batchOperating(@RequestBody  RunfastGoodsSell sell ){
        if(sell!=null && sell.getIds()!=null && sell.getIds().size()>0){
            for(Integer in:sell.getIds()){
                RunfastGoodsSell goodsSell=runfastGoodsSellService.selectByPrimaryKey(in);

                if(goodsSell!=null){
                    Map<Object,Object> map =runfastGoodsSellService.selectBygoodsId(goodsSell);
                    goodsSell.setStandardList((List<RunfastGoodsSellStandard>)map.get("standards"));
                    goodsSell.setOptionList((List<RunfastGoodsSellOption>)map.get("optionList"));
                    if(sell.getOptionList().size()>0){
                       //批量修改属性
                        List<RunfastGoodsSellOption> optionList=goodsSell.getOptionList();
                        if(optionList.size()>0){
                            for(RunfastGoodsSellOption option:optionList){
                                if(option.getSellSubOptionList().size()>0){
                                    for(RunfastGoodsSellSubOption subOption:option.getSellSubOptionList()){
                                        subOption.setDel(1);
                                        runfastGoodsSellSubOptionService.updateByPrimaryKeySelective(subOption);
                                    }
                                }
                                option.setDeleted(true);
                                runfastGoodsSellOptionService.updateByPrimaryKeySelective(option);
                            }
                        }
                        for(RunfastGoodsSellOption option:sell.getOptionList()){
                            RunfastGoodsSellOption option1=new RunfastGoodsSellOption();
                            option1.setBusinessid(goodsSell.getBusinessid());
                            option1.setGoodssellid(goodsSell.getId());
                            option1.setBusinessname(goodsSell.getBusinessname());
                            option1.setGoodssellname(goodsSell.getName());
                            option1.setDeleted(false);
                            option1.setName(option.getName());
                            runfastGoodsSellOptionService.insert(option1);
                            if(option.getSellSubOptionList().size()>0){
                                for(RunfastGoodsSellSubOption subOption:option.getSellSubOptionList()){
                                    RunfastGoodsSellSubOption subOption1=new RunfastGoodsSellSubOption();
                                    subOption1.setDel(0);
                                    subOption1.setOptionid(option1.getId());
                                    subOption1.setBusinessid(option1.getBusinessid());
                                    subOption1.setGoodssellid(option1.getGoodssellid());
                                    subOption1.setGoodssellname(option1.getGoodssellname());
                                    subOption1.setBusinessname(option1.getBusinessname());
                                    subOption1.setOptionname(option1.getName());
                                    subOption1.setName(subOption.getName());
                                    runfastGoodsSellSubOptionService.insert(subOption1);
                                }
                            }
                        }
                    }else if(sell.getStandardList().size()>0){
                       //批量修改规格
                         List<RunfastGoodsSellStandard> standards=goodsSell.getStandardList();
                         if(standards.size()>0){
                             for(RunfastGoodsSellStandard standard:standards){
                                 standard.setDeleted(true);
                                 runfastGoodsSellStandardService.updateByPrimaryKeySelective(standard);
                             }
                         }
                         for(RunfastGoodsSellStandard standard:sell.getStandardList()){
                             standard.setBusinessid(goodsSell.getBusinessid());
                             standard.setGoodssellid(goodsSell.getId());
                             standard.setBusinessname(goodsSell.getBusinessname());
                             if(standard.getFullNum()==null){
                                 standard.setFullNum(false);
                             }
                             standard.setDeleted(false);
                             runfastGoodsSellStandardService.insert(standard);
                         }
                    }else if(sell.getPackageFee()!=null){
                        //批量修改餐盒费
                        RunfastGoodsSellStandardExample example=new RunfastGoodsSellStandardExample();
                        example.createCriteria().andDeletedNotEqualTo(true).andBusinessidEqualTo(goodsSell.getBusinessid()).andGoodssellidEqualTo(goodsSell.getId());
                        List<RunfastGoodsSellStandard> standards=runfastGoodsSellStandardService.selectByExample(example);
                        if(standards.size()>0){
                            for(RunfastGoodsSellStandard standard:standards){
                                standard.setPackageFee(sell.getPackageFee());
                                runfastGoodsSellStandardService.updateByPrimaryKeySelective(standard);
                            }
                        }
                    }else if(sell.getSelltypeid()!=null){
                        // 批量修改商品分类
                        goodsSell.setSelltypeid(sell.getSelltypeid());
                        runfastGoodsSellService.updateByPrimaryKeySelective(goodsSell);
                    }
                }else{return Result.fail(null,"未找到对应的商品！");}
            }
        }
        return Result.ok(null);
    }

    /**拖动排序*/
    @PostMapping("/dragSort")
    public Result dragSort(@RequestBody RunfastGoodsSell sell){
        if(sell!=null && sell.getIds()!=null &&sell.getBusinessid()!=null){

            int i=0;
            for(Integer in:sell.getIds()){
                RunfastGoodsSell type1=new RunfastGoodsSell();
                type1.setId(in);
                type1.setSort(i);
                runfastGoodsSellService.updateByPrimaryKeySelective(type1);
                i++;
            }
        }
        return Result.ok(null);
    }


    /**选择商品*/
    @GetMapping("/selectGoodsSell")
    public Result selectGoodsSell(@PageableDefault Pageable pageable,String name,Integer agentid){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        RunfastBusinessAccounts accounts = SessionContext.getRunfastBusinessAccounts();
        RunfastGoodsSellExample example=new RunfastGoodsSellExample();
        RunfastGoodsSellExample.Criteria exampleCriteria=example.createCriteria();
        exampleCriteria.andStatusEqualTo(0);
        if(StringUtils.isNotBlank(name)){
            exampleCriteria.andNameLike(""+name+"");
        }
        if(agentid!=null){
            exampleCriteria.andAgentidEqualTo(agentid);
        }
        if(admin!=null && admin.getType()==1){
            //所有商家
        }else if(admin!=null && admin.getType()==2 && agentAccounts!=null){
            //代理商
            exampleCriteria.andAgentidEqualTo(agentAccounts.getAgentid());
        }else if(admin!=null && admin.getType()==3 && accounts!=null){
            //商家
            exampleCriteria.andIdEqualTo(accounts.getBusinessid());
        }
        List<RunfastGoodsSell> list=runfastGoodsSellService.selectByExampleWithPageable(example,pageable);
        /*if(list.size()>0){
            for(RunfastBusiness business:list){
                if(business!=null && business.getAgentid()!=null){
                    WaiMaiRunfastAgentbusiness  agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(business.getAgentid());
                    if(agentbusiness!=null){
                        business.setAgentname(agentbusiness.getName());
                    }
                }
            }
        }*/
        Integer total=runfastGoodsSellService.countByExample(example);
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("total",total);
        map.put("list",list);
        return Result.ok(null,map);
    }


}
